<template>
  <div class="down-query-root">
<!--    <div class="dict-item active" v-if="hierarchy > 1">-->
<!--      {{ dataTxt }}-->
<!--    </div>-->
    <div :class="[`dict-item`,`dict-item-${id}`,`dict-item-${id}-${item.value}`]" @click="itemClick(item)"
         v-for="(item,index) in dataList"
         :key="index">
      {{ item.label }}
    </div>
    <div v-if="hierarchy > 1" class="dict-item" @click="goBack">返回</div>
  </div>
</template>

<script>
import guid from "@/utils/guid";
import {isArr} from "@/utils/arrayUtil";
import {NODE_TYPE} from "@/constantData";

export default {
  props: {
    value: {
      type: Object
    },
    getDataList: {
      type: Function,
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      checkData: null,
      id: `p-${guid()}`,
      dataList: [],
      currentDataItem: null,
      hierarchy: 0,
      queryDataList: [],
    }
  },
  computed: {
    dataTxt() {
      let {queryDataList} = this
      return queryDataList.filter(item => item).map(item => item.label).join('-')
    }
  },
  methods: {
    isArr,
    goBack() {
      let queryItem = this.queryDataList[this.hierarchy - 2]
      this.queryDataList = this.queryDataList.splice(0, this.queryDataList.length - 2);
      this.hierarchy -= 2
      this.hierarchy = this.hierarchy >= 0 ? this.hierarchy : 0
      this.itemClick(queryItem);
    },
    itemClick(dataItem) {
      let {getDataList} = this
      this.currentDataItem = dataItem
      this.$emit('change', this.currentDataItem)
      this.changeClassList(dataItem?.value);

      if (dataItem?.isLeaf == NODE_TYPE.LEAF || getDataList == null || typeof getDataList !== 'function') return;
      let lastChild = isArr(this.queryDataList) ? this.queryDataList[this.queryDataList.length - 1] : null
      if (this.hierarchy == 0 || lastChild?.value !== dataItem?.value) {
        this.queryDataList.push(dataItem);
        this.hierarchy += 1;
      }
      let owner = this
      getDataList(dataItem).then(res => {
        owner.dataList = res.data
      });
    },
    changeClassList(dictValue) {
      let {id} = this
      let domList = document.getElementsByClassName(`dict-item-${id}`)
      if (isArr(Array.from(domList))) {
        Array.from(domList).forEach(cDom => {
          cDom.classList.remove('active')
        })
      }
      let dom = document.querySelector(`.dict-item-${id}-${dictValue}`);
      if (!dom) return;
      dom.classList.add('active')
    },
  },
  created() {
    this.currentDataItem = this.value;
    this.itemClick(this.currentDataItem)
  }
}
</script>

<style scoped>

</style>
